package com.kaishengit.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaishengit.entity.User;

public class LoginFilter extends AbstrictFilter {
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest  req= (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String uri = req.getRequestURI();
		uri = uri.substring(uri.lastIndexOf("/")+1);
		if("".equals(uri) || "index.jsp".equals(uri)||"login.jspx".equals(uri)||uri.endsWith(".css")||uri.endsWith(".js")||uri.endsWith(".jpg")||uri.endsWith("png")||uri.equals("gif")){
			chain.doFilter(request, response);
		}else{
			HttpSession session = req.getSession();
			User user = (User) session.getAttribute("user");
			
			if(user == null){
				//当没有登录用户的时候，
				//获取当前用户的想要去的地方，当用户登录的时候，就直接去访问这个地址
				//获取？号以后的地址
				String queryString = req.getQueryString();
				//获取问号以前的绝对地址
				String url = req.getRequestURL().toString();
				if(queryString != null){
					//将以上的两个地址进行连加，可得到用户想要去的地方
					url = url+"?"+queryString;
				}
				//将这个地方放到session中，
				session.setAttribute("where", url);
				//没有登录的用户既可以重定向到本地的路径，或者是其他的路径，如谷歌等
				resp.sendRedirect("login.jspx?code=10001");
			}else{
				chain.doFilter(request, response);	
			}
			
			
		}
	}
}
